import React from 'react';
import { Form, Input, Checkbox, Tag, message } from 'antd';
import { BorderOuterOutlined, UpOutlined, DownOutlined } from '@ant-design/icons';
import CommonModalForm from '@/components/CommonModalForm';
// import { querypullDownList } from '@/services/management.service';
import { goodsInfo, listType, children, topCateInfo } from './type';
import './index.less';

type TProps = {
  visible: boolean;
  selectGoodsInfo: goodsInfo;
  confirmLoading: boolean;
  isMoreChoice?: boolean; // 是否开启多选
  onSubmit: any;
  onCancel: any;
};

const ChoseGoods: React.FC<TProps> = (props) => {
  const {
    visible,
    selectGoodsInfo,
    confirmLoading,
    isMoreChoice = false,
    onCancel,
    onSubmit,
  } = props;
  const [form] = Form.useForm();
  const [selectTopCate, setSelectTopCate] = React.useState<number>(-1);
  const [selectSecoundCate, setSelectSecoundCate] = React.useState<number>(-1);
  const [goodsId, setGoodsId] = React.useState(-1);
  const [goodsIds, setGoodsIds] = React.useState<string[]>([]);
  const [goods, setGoods] = React.useState<any[]>([]);
  const [list, setList] = React.useState<listType[]>([]);

  const defaultDatas: any = [
    {
      name: '商城商品',
      id: 0,
      children: [
        {
          value: '虚拟商品',
          id: 0,
          goods: [],
        },
        {
          value: '实物商品',
          id: 1,
          goods: [],
        },
      ],
    },
  ];

  const init = async (type: number) => {
    const params: any = {
      type, // 0 虚拟商品 1 实物商品
    };
    try {
      // const { code, message: msg, data } = await querypullDownList(params);
      // if (code === 0) {
      //   if (data.length > 0) {
      //     data.forEach((ele: any) => {
      //       defaultDatas[0].children[type].goods.push(ele);
      //     });
      //     setList(defaultDatas);
      //   }
      // } else {
      //   message.error(msg);
      // }
    } catch (error) {}
  };

  React.useEffect(() => {
    init(0);
  }, []);

  // 编辑进来
  React.useEffect(() => {
    // todo 单选和多选
    if (isMoreChoice) {
      const ids: string[] = [];
      selectGoodsInfo.goodsData.forEach((e: any) => {
        ids.push(e.id);
      });
      setGoodsIds(ids);
    } else {
      if (selectGoodsInfo.id) {
        setGoodsId(selectGoodsInfo.id);
      } else {
        setGoodsId(-1);
      }
    }
  }, [selectGoodsInfo]);

  React.useEffect(() => {
    // 根据一二级分类筛选商品
    if (selectTopCate > -1 && selectSecoundCate > -1 && list.length > 0) {
      const topIndex = list.findIndex((item) => item.id === selectTopCate);
      const secoundIndex = list[topIndex].children.findIndex(
        (item: children) => item.id === selectSecoundCate,
      );
      setGoods(list?.[topIndex]?.children?.[secoundIndex]?.goods || []);
    }
  }, [selectTopCate, selectSecoundCate, list]);

  // 选择一级分类
  const handleChooseTopCate = (item: topCateInfo) => {
    setSelectTopCate(item.id);
  };

  // 选择二级分类
  const handleChooseSecoundCate = (val: children) => {
    setSelectSecoundCate(val.id);
    init(val.id);
  };

  // 选择商品
  const handleChange = (e: any) => {
    // 如果是多选
    if (isMoreChoice) {
      const ids = goodsIds.concat([]);
      if (e.target.checked) {
        ids.push(e.target.value);
      } else {
        const index = ids.findIndex((id) => id === e.target.value);
        ids.splice(index, 1);
      }
      setGoodsIds(ids);
    } else {
      setGoodsId(e.target.value);
    }
  };

  // 取消
  const handleCancel = () => {
    if (selectGoodsInfo.id !== goodsId) {
      setGoodsId(selectGoodsInfo.id);
    }
    onCancel();
  };

  const handleSubmit = () => {
    if (isMoreChoice) {
      const info: any = {
        id: '',
        title: '',
        goodsData: [],
        cateId: selectTopCate,
        secoundCateId: selectSecoundCate,
      };
      goods.forEach((item) => {
        if (goodsIds.includes(item.productNo)) {
          info.goodsData.push({
            id: item.productNo,
            value: item,
          });
        }
      });
      onSubmit(info);
    } else {
      const obj = goods.find((item) => item.productNo === goodsId);
      const info = {
        id: goodsId,
        title: obj.productName,
        goodsData: [],
        cateId: selectTopCate,
        secoundCateId: selectSecoundCate,
      };
      onSubmit(info);
    }
  };

  // 搜索
  const handleInputChange = async (e: any) => {
    if (selectSecoundCate > -1) {
      const params: any = {
        type: 0, // 0 虚拟商品 1 实物商品
        productNoOrName: e.target.value,
      };
      // const { code, message: msg, data } = await querypullDownList(params);
      // if (code === 0) {
      //   setGoods(data);
      // } else {
      //   message.error(msg);
      // }
    }
  };

  return (
    <CommonModalForm
      formRef={form}
      visible={visible}
      confirmLoading={confirmLoading}
      okText={'确定'}
      title={'选择商品'}
      onSubmit={handleSubmit}
      onCancel={handleCancel}
      width={720}
      formProps={{
        layout: 'vertical',
        autoComplete: 'off',
      }}
      okButtonProps={{
        disabled: isMoreChoice
          ? !(goodsIds.length > 0)
          : !(selectTopCate > -1 && selectSecoundCate > -1 && goodsId > -1),
      }}
    >
      <div className="chooseContent">
        <div className="chooseGoods">
          {/* 分类 */}
          <div className="selectGoodsCate">
            {list.map((item, index) => {
              return (
                <div className="cateContent" key={index}>
                  {/* 一级分类 */}
                  <div
                    className={`topCate ${selectTopCate === item.id && 'selectTopCate'}`}
                    onClick={() => handleChooseTopCate(item)}
                  >
                    <BorderOuterOutlined className="cateIcon" />
                    <span className="cateName">{item.name}</span>
                    {selectTopCate === item.id ? (
                      <DownOutlined className="cateArrow" />
                    ) : (
                      <UpOutlined className="cateArrow" />
                    )}
                  </div>
                  {/* 二级分类 */}
                  <div
                    className="secoundCateContent"
                    style={{ height: selectTopCate === item.id ? 'auto' : '0' }}
                  >
                    {item.children.map((val: children, num: number) => (
                      <div
                        className={`secoundCate ${
                          selectSecoundCate === val.id && 'selectSecoundCate'
                        }`}
                        key={num}
                        onClick={() => handleChooseSecoundCate(val)}
                      >
                        {val.value}
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
          <div className="selectGoods">
            <div className="searchInt">
              <Input
                className="int"
                type="text"
                placeholder="请输入要查找的商品名或商品ID"
                onChange={handleInputChange}
              />
            </div>
            {goods.length > 0 &&
              goods.map((item: any, index: number) => {
                return (
                  <div className="selectGoodsItem" key={index}>
                    <Checkbox
                      value={item.productNo}
                      onChange={handleChange}
                      checked={
                        isMoreChoice
                          ? goodsIds.includes(item.productNo)
                          : item.productNo === goodsId
                      }
                    >
                      <div className="goodsInfo">
                        <span className="goodsName">{item.productName}</span>
                        <span className="goodsId">{item.productNo}</span>
                      </div>
                    </Checkbox>
                    <Tag color="green">已上架</Tag>
                  </div>
                );
              })}
          </div>
        </div>
      </div>
    </CommonModalForm>
  );
};

export default ChoseGoods;
